﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EComAssignment.Models;
using System.IO;
using EComAssignment.Filter;
using System.Web.Routing;

namespace EComAssignment.Controllers
{
    [CustomAuthorization(UserLevel = new int[] { 0, 1 })]
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        
        public ActionResult ProductDetail(int? proID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "ProductList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cate = (from c in ctx.Categories
                        select new { c.ID, c.name });
            
            Dictionary<int, string> category = new Dictionary<int, string>();
            Dictionary<int, IQueryable<string>> groupName = new Dictionary<int, IQueryable<string>>();
            foreach (var c in cate)
            {
                var group = (from p in ctx.Products
                                 where p.category_ID == c.ID
                                 select p.group_name).Distinct();
                category.Add(c.ID, c.name);
                groupName.Add(c.ID, group);
            }
            ViewBag.category = category;
            ViewBag.groupName = groupName;

            var pro = (from p in ctx.Promotions
                       select new {p.ID,p.title}.ToExpando());
            ViewBag.promotion = pro;

            if (proID != null)
            {
                var product = (from p in ctx.Products
                               where p.ID == proID
                               select p).SingleOrDefault();
                if (product != null)
                {
                    return View(product);
                }
            }
            
            return View(new Product());
        }

        public ActionResult getGroupName()
        {
            string cateID = Request.QueryString["cateID"];
            int categoryID = -1;
            try
            {
                categoryID = Int32.Parse(cateID);
            }
            catch (Exception) { }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var group = (from p in ctx.Products
                         where p.category_ID == categoryID
                         select p.group_name).Distinct();
            ViewBag.group = group; 
            return View();
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0 })]
        public ActionResult ProductDetailClick(int capacity = 0)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "ProductList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            
            string ID = Request.Form["proID"];
            int proID = 0;
            try
            {
                proID = Int32.Parse(ID);
            }
            catch (Exception) { }
            string name = Request.Form["proName"];
            string category = Request.Form["category"];
            int cateID = 0;
            try
            {
                cateID = Int32.Parse(category);
            }
            catch (Exception) { }
            string groupName = Request.Form["group_name"];
            string type = Request.Form["type"];
            string vol = Request.Form["volume"];
            int volume = 0;
            try
            {
                volume = Int32.Parse(vol);
            }
            catch (Exception) { }
            string amo = Request.Form["amount"];
            int amount = 0;
            try
            {
                amount = Int32.Parse(amo);
            }
            catch (Exception) { }
            string pri = Request.Form["price"];
            decimal price = 0;
            try
            {
                price = decimal.Parse(pri);
            }
            catch (Exception) { }
            string description = Request.Form["description"];
            string isPromotion = Request.Form["is_promotion"];
            int? promotionID = null;
            if (isPromotion != null)
            {
                try
                {
                    promotionID = Int32.Parse(Request.Form["promotion"]);
                }
                catch (Exception) { }
            }
            var file = Request.Files["image_link"];
            string fileName = AdminModel.saveImage(file, Server);
            bool isSelling = Request.Form["is_selling"] != null ? true : false;
            bool success = AdminModel.saveProduct(proID, name, description, cateID, type, volume,capacity, price, amount,
                fileName, promotionID, groupName, isSelling);
            if (success)
            {
            }
            if (proID > 0)
            {
                RouteValueDictionary data = new RouteValueDictionary();
                data.Add("proID",proID);
                return RedirectToAction("ProductDetail", "Admin", data);
            }
            return RedirectToAction("ProductDetail", "Admin");
        }

        
        public ActionResult ProductList(int? pageNum)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "ProductList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var proList = (from p in ctx.Products
                           orderby p.sell_start_date descending
                           select p);
            if (pageNum == null) { pageNum = 1; }
            int maxProNum = 8;
            int skipNum = (int)(maxProNum * (pageNum - 1));
            ViewBag.maxPage = (proList.Count() - 1) / maxProNum + 1;
            ViewBag.currentPage = pageNum;

            ViewBag.proList = proList.Skip(skipNum).Take(maxProNum); 
            return View();
        }

        [CustomAuthorization(UserLevel = new int[] { 0 })]
        public ActionResult DeleteProduct()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;   
                ViewBag.action = "ProductList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            string id = Request.QueryString["proID"];
            int proID = 0;
            try
            {
                proID = Int32.Parse(id);
            }
            catch (Exception) { }
            AdminModel.deleteProduct(proID,Server);
            return RedirectToAction("ProductList", "Admin");
        }

        public ActionResult CategoryList()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                RouteValueDictionary data = new RouteValueDictionary();
                ViewBag.action = "CategoryList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cateList = (from c in ctx.Categories
                           orderby c.name ascending
                           select c);
            ViewBag.cateList = cateList;
            return View();
        }

        public ActionResult CategoryDetail(int? cateID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "CategoryList";
                ViewBag.controller = "Admin";
                return View("Login");
            }

            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cate = (from c in ctx.Categories                        
                        where c.ID == cateID
                        select c).SingleOrDefault();            

            if (cate != null)
            {
                return View(cate);
            }

            return View(new Category());
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0 })]
        public ActionResult CategoryDetailClick()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "CategoryList";
                ViewBag.controller = "Admin";
                return View("Login");
            }

            string ID = Request.Form["cateID"];
            int cateID = 0;
            try
            {
                cateID = Int32.Parse(ID);
            }
            catch (Exception) { }
            string name = Request.Form["cateName"];
            string address = Request.Form["address"];
            string phoneNum = Request.Form["phoneNum"];

            var file = Request.Files["image_link"];
            string imgName = AdminModel.saveCateImage(file, Server);
            string description = Request.Form["description"];
            string email = Request.Form["email"];
            string website = Request.Form["website"];
            bool success = AdminModel.saveCategory(cateID, name, address, phoneNum, imgName, description, email, website);
            if (success)
            {
            }
            return RedirectToAction("CategoryList", "Admin");
        }

        [CustomAuthorization(UserLevel = new int[] { 0 })]
        public ActionResult DeleteCategory(int cateID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "CategoryList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            
            AdminModel.deleteCategory(cateID);
            return RedirectToAction("CategoryList", "Admin");
        }

        public ActionResult AccountList(int? pageNum)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "AccountList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var accList = (from a in ctx.Accounts
                            orderby a.user_level ascending, a.username ascending
                            select a);
            if (pageNum == null) { pageNum = 1; }
            int maxProNum = 10;
            int skipNum = (int)(maxProNum * (pageNum - 1));
            ViewBag.maxPage = (accList.Count() - 1) / maxProNum + 1;
            ViewBag.currentPage = pageNum;
            ViewBag.accList = accList.Skip(skipNum).Take(maxProNum);
            return View();
        }

        public ActionResult AccountDetail(int? accID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "AccountList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            ViewBag.error = Request.QueryString["error"];
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var acc = (from a in ctx.Accounts
                        where a.ID == accID
                        select a).SingleOrDefault();

            if (acc != null)
            {
                return View(acc);
            }

            return View(new Account());
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0 })]
        public ActionResult AccountDetailClick()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "AccountList";
                ViewBag.controller = "Admin";
                return View("Login");
            }

            string ID = Request.Form["accID"];
            int accID = 0;
            try
            {
                accID = Int32.Parse(ID);
            }
            catch (Exception) { }
            string username = Request.Form["username"];
            string password = Request.Form["password"];
            string fullName = Request.Form["fullName"];
            string address = Request.Form["address"];
            string email = Request.Form["email"];
            string phoneNum = Request.Form["phoneNum"];
            string level = Request.Form["userLevel"];
            int userLevel = 0;
            try
            {
                userLevel = Int32.Parse(level);
            }
            catch (Exception) { }
            bool success = AdminModel.saveAccount(accID,username,password,fullName,email,address,phoneNum,userLevel);
            if (!success)
            {
                RouteValueDictionary data = new RouteValueDictionary();
                data.Add("accID", accID);
                data.Add("error", "Tên tài khoản đã tồn tại");
                return RedirectToAction("AccountDetail", "Admin", data);
            }
            return RedirectToAction("AccountList", "Admin");
        }

        [CustomAuthorization(UserLevel = new int[] { 0 })]
        public ActionResult DeleteAccount(int accID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "AccountList";
                ViewBag.controller = "Admin";
                return View("Login");
            }

            AdminModel.deleteAccount(accID);
            return RedirectToAction("AccountList", "Admin");
        }

        public ActionResult adminOrderList(int? pageNum)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }

            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var orderList = (from o in ctx.Orders
                             orderby o.status descending, o.order_date descending                             
                             select o);
            if (pageNum == null) { pageNum = 1; }
            int maxProNum = 10;
            int skipNum = (int)(maxProNum * (pageNum - 1));
            ViewBag.maxPage = (orderList.Count() - 1) / maxProNum + 1;
            ViewBag.currentPage = pageNum;
            ViewBag.orderList = orderList.Count() > 0 ? orderList.Skip(skipNum).Take(maxProNum) : null;
            return View();
        }

        public ActionResult OrderChangeStatus(int orderID, string status)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            bool success = AdminModel.changeOrderStatus(orderID, status);
            if (success) { }
            
            return RedirectToAction("adminOrderList", "Admin");
        }

        public ActionResult feedbackList(int? pageNum)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var fbList = (from f in ctx.Feedbacks
                          orderby f.status descending, f.feedback_date descending
                          select f);
            if (pageNum == null) { pageNum = 1; }
            int maxProNum = 10;
            int skipNum = (int)(maxProNum * (pageNum - 1));
            ViewBag.maxPage = (fbList.Count() - 1) / maxProNum + 1;
            ViewBag.currentPage = pageNum;
            return View(fbList.Skip(skipNum).Take(maxProNum));
        }

        public ActionResult DeleteFeedback(int id)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            bool success = AdminModel.deleteFeedback(id);
            if (success) { }
            return RedirectToAction("feedbackList", "Admin");
        }

        public ActionResult FeedbackDetail(int id)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var feedback = (from fb in ctx.Feedbacks
                            where fb.ID == id
                            select fb).SingleOrDefault();
            if (feedback == null) { feedback = new Feedback(); }
            return View(feedback);
        }

        [HttpPost]
        public ActionResult FeedbackDetailClick(int fbID, string fbAnswer)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            bool success = AdminModel.answerFeedback(fbID, fbAnswer);
            if (success) { }
            return RedirectToAction("feedbackList", "Admin");
        }

        public ActionResult SliderList()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var slider = (from s in ctx.Sliders
                          select s);
            if (slider.Count() == 0)
            {
                slider = null;
            }
            return View(slider);
        }

        [HttpPost]
        public ActionResult AddSlider()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            var file = Request.Files["image_link"];
            string fileName = AdminModel.saveSlider(file, Server);
            AdminModel.addSlider(fileName);
            return RedirectToAction("SliderList", "Admin");
        }

        public ActionResult removeSlider(int id)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");                               
            }
            bool success = AdminModel.RemoveSlider(id, Server);
            if (success) { }
            return RedirectToAction("SliderList", "Admin");
        }

        public ActionResult deleteComment(int proID, int cmtID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                bool isUserComment = MainModel.isUserComment(cmtID, (string)Session["username"]);
                if (!isUserComment)
                {
                    ViewBag.action = "personal";
                    ViewBag.controller = "Account";
                    return View("Login");
                }
            }
            MainModel.deleteComment(cmtID);
            RouteValueDictionary data = new RouteValueDictionary();
            data.Add("proID", proID);
            return RedirectToAction("CommentView", "Main", data);
        }

        public ActionResult promotionList(string error)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            if (error != null) { ViewBag.error = error; }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var promoList = (from p in ctx.Promotions
                             select p);
            if (promoList.Count() == 0) { promoList = null; }
            return View(promoList);
        }

        [HttpPost]
        public ActionResult DeletePromotion(int promoID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            bool success = AdminModel.deletePromotion(promoID);
            if (!success)
            {
                RouteValueDictionary data = new RouteValueDictionary();
                data.Add("error", "Không thể xóa vì khuyến mãi đang được áp dụng");
                return RedirectToAction("promotionList", "Admin",data);
            }
            return RedirectToAction("promotionList","Admin");
        }

        public ActionResult PromotionDetail(int? promoID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var promo = ctx.Promotions.Where(p => p.ID == promoID).SingleOrDefault();
            if (promo == null)
            {
                promo = new Promotion() 
                {  
                    start_date = DateTime.Now,
                    end_date = DateTime.Now
                };
            }
            return View(promo); 
        }

        [HttpPost]
        public ActionResult PromotionDetailClick(int? promoID, string promoTitle, string description,
            int rate, string startDate, string endDate)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            bool success = AdminModel.savePromotion(promoID, promoTitle, description, rate, startDate, endDate);
            if (success) { }
            return RedirectToAction("promotionList", "Admin");
        }

        [HttpPost]
        public ActionResult deleteRating(int proID, int rateID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            MainModel.deleteRating(rateID);
            RouteValueDictionary data = new RouteValueDictionary();
            data.Add("proID", proID);
            return RedirectToAction("RatingView", "Main", data);
        }

        public ActionResult MapsList()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "MapsList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var lo = (from l in ctx.Locations
                      select l);
            if (lo.Count() == 0) { lo = null; }
            return View(lo);
            //foreach (var m in lo) {m.lng }
        }

        [HttpPost]
        public ActionResult saveMaps(string name, string address, string position)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "MapsList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            bool success = AdminModel.saveMaps(name, address, position);
            if (success) { }
            return RedirectToAction("MapsList", "Admin");
        }

        [HttpPost]
        public ActionResult deleteMaps(int mapID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "MapsList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            bool success = AdminModel.deleteMaps(mapID);
            if (success) { }
            return RedirectToAction("MapsList", "Admin");
        }

        [HttpPost]
        public ActionResult updateMaps(int mapID, string address, string position)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "MapsList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            bool success = AdminModel.updateMaps(mapID,address,position);
            if (success) { }
            return RedirectToAction("MapsList", "Admin");
        }

        [HttpPost]
        public bool sendSMSProcessing(int orderID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                return false;
            }
            bool success = AdminModel.sendSMSToOrderProcessing(orderID);
            return success;
        }

        public ActionResult newsView(int? ID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "newsView";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var news = ctx.News.Where(n => n.ID == ID).SingleOrDefault();
            if (news == null) { news = new New(); }
            return View(news);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult postNews(int ID, string title, string body)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "newsView";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            int resultID = AdminModel.saveNews(ID, title, body);
            if (resultID > 0) 
            {
                RouteValueDictionary data = new RouteValueDictionary();
                data.Add("id", resultID);
                return RedirectToAction("NewsDetail", "Main", data);
            }
            return RedirectToAction("newsView", "Admin");
        }

        public ActionResult newsList(int? pageNum)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "newsList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var list = (from n in ctx.News
                        orderby n.post_date descending
                        select new {n.ID,n.title,n.post_date }.ToExpando());
            if (pageNum == null) { pageNum = 1; }
            int maxProNum = 10;
            int skipNum = (int)(maxProNum * (pageNum - 1));
            ViewBag.maxPage = (list.Count() - 1) / maxProNum + 1;
            ViewBag.currentPage = pageNum;
            if (list.Count() == 0) { return View(); }
            return View(list.Skip(skipNum).Take(maxProNum)); 
        }

        [HttpPost]
        public ActionResult deleteNews(int ID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "newsList";
                ViewBag.controller = "Admin";
                return View("Login");
            }
            bool success = AdminModel.deleteNews(ID);
            if (success) { }
            return RedirectToAction("newsList","Admin");
        }
    }
}
